import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/user";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "layout",
      component: () => import("@/views/Layout/index.vue"),
      children: [
        {
          path: "/", //默认就是Home页面
          component: () => import("@/views/Home/index.vue"),
        },
        {
          path: "/category/:id",
          component: () => import("@/views/Category/index.vue"),
        },
        {
          path: "/category/sub/:id",
          component: () => import("@/views/SubCategory/index.vue"),
        },
        {
          path: "/detail/:id",
          component: () => import("@/views/Detail/index.vue"),
        },
        {
          path: "/cart",
          component: () => import("@/views/Cart/index.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login/index.vue"),
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});
router.beforeEach((to) => {
  const userStore = useUserStore();
  if (!userStore.userInfo.token && to.path !== "/login") {
    return "/login";
  }
});

export default router;
